package com.project.filter;


import com.project.common.RoleType;
import com.project.redis.RedisCache;
import com.project.security.LoginUserInfo;
import com.project.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 *  OncePerRequestFilter : 请求只会经过这个过滤器一次
 */
@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
                                    @NotNull FilterChain filterChains) throws ServletException, IOException {


        try {
            // 获取 token
            String token = request.getHeader("Authentication");
            log.info("token:{}", token);

            if (!StringUtils.hasLength(token)) {
                // token 为空, 放行
                filterChains.doFilter(request, response);
                return;
            }

            // 验证token
            Claims claims = JwtUtil.parseJWT(token);
            // 获取用户id
            String userid = claims.get("userId").toString();
            log.info("userId:{}", userid);
            // 获取角色类型
            String roleType = claims.get("roleType").toString();
            log.info("roleType:{}", roleType);
            // 从 redis 中获取用户信息
            String redisKey = roleType + "-" + userid;
            if (RoleType.ROLE_USER.equals(roleType)) {
                LoginUserInfo loginUser = redisCache.getCacheObject(redisKey);
                log.info("loginUser:{}", loginUser);
                if (Objects.isNull(loginUser)) {
                    // token 认证失败.
                    throw new AuthenticationServiceException("认证失败!");
                }
                // 存入 SecurityContextHolder
                UsernamePasswordAuthenticationToken authenticationToken =
                        // 必须使用三个参数的构造方法 -> 标志用户已认证
                        new UsernamePasswordAuthenticationToken(loginUser, loginUser.getUser().getPassword(), loginUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            } else {
                throw new AuthenticationServiceException("认证失败!");
            }
            // 放行
            filterChains.doFilter(request, response);
        } catch (Exception e) {
                log.error(e.getMessage());
                filterChains.doFilter(request, response);
        }
    }

//    @Override
//    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChains) throws IOException, ServletException {
//
//        HttpServletRequest request = (HttpServletRequest) servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//
//        try {
//
//
//            // 获取 token
//            String token = request.getHeader("Authentication");
//            log.info("token:{}", token);
//
//            if (!StringUtils.hasLength(token)) {
//                // token 为空, 放行
//                filterChains.doFilter(request, response);
//                return;
//            }
//
//            // 验证token
//            Claims claims = JwtUtil.parseJWT(token);
//            // 获取用户id
//            String userid = claims.get("userId").toString();
//            log.info("userId:{}", userid);
//            // 获取角色类型
//            String roleType = claims.get("roleType").toString();
//            log.info("roleType:{}", roleType);
//            // 从 redis 中获取用户信息
//            String redisKey = roleType + "-" + userid;
//            if (RoleType.ROLE_USER.equals(roleType)) {
//                LoginUserInfo loginUser = redisCache.getCacheObject(redisKey);
//                log.info("loginUser:{}", loginUser);
//                if (Objects.isNull(loginUser)) {
//                    // token 认证失败.
//                    throw new AuthenticationServiceException("认证失败!");
//                }
//                // 存入 SecurityContextHolder
//                UsernamePasswordAuthenticationToken authenticationToken =
//                        // 必须使用三个参数的构造方法 -> 标志用户已认证
//                        new UsernamePasswordAuthenticationToken(loginUser, loginUser.getUser().getPassword(), loginUser.getAuthorities());
//                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
//            } else {
//                throw new AuthenticationServiceException("认证失败!");
//            }
//            // 放行
//            filterChains.doFilter(request, response);
//        } catch (Exception e) {
//            log.error(e.getMessage());
//            filterChains.doFilter(request, response);
//        }
//    }
}